package models

import (
	"gorm.io/gorm"
)

type Tag struct {
	TagID int `gorm:"primary_key"  json:"tag_id"`

	TagName       string `json:"tag_name"`
	InstitutionID int    `json:"institution_id"`
}

// TableName 表名称
func (*Tag) TableName() string {
	return "tag"
}

// GetTag 查询多条数据
func GetTag(fields []string, maps map[string]interface{}) ([]*Tag, error) {
	var address []*Tag
	cond, vals, errs := WhereBuild(maps)
	if errs != nil {
		return nil, errs
	}
	err := db.Select(fields).Where(cond, vals...).Take(&address).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return address, nil
}

func GetTagPage(fields []string, maps map[string]interface{}, pageNum int, pageSize int, order string) ([]*Tag, error) {
	var Tag []*Tag
	cond, vals, errs := WhereBuild(maps)
	if errs != nil {
		return nil, errs
	}
	err := db.Select(fields).Where(cond, vals...).Offset(pageNum).Limit(pageSize).Order(order).Find(&Tag).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return Tag, nil
}

// GetTagInfo 查询多条数据
func GetTagInfo(fields []string, maps map[string]interface{}) (*Tag, error) {
	var Tag Tag
	cond, vals, errs := WhereBuild(maps)
	if errs != nil {
		return nil, errs
	}
	err := db.Select(fields).Where(cond, vals...).Take(&Tag).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &Tag, nil
}

// AddTag 插入数据
func AddTag(data map[string]interface{}) (int, error) {
	tag := Tag{
		TagName:       data["tag_name"].(string),
		InstitutionID: data["institution_id"].(int),
	}
	result := db.Select("tag_name", "institution_id").Create(&tag)
	if err := result.Error; err != nil {
		return 0, err
	}
	return tag.TagID, nil
}

// EditTag modify a single Tag
func EditTag(where map[string]interface{}, data interface{}) error {
	cond, vals, errs := WhereBuild(where)
	if errs != nil {
		return errs
	}
	if err := db.Model(&Tag{}).Where(cond, vals...).Updates(data).Error; err != nil {
		return err
	}
	return nil
}

func GetTagTotal(where map[string]interface{}) (int64, error) {
	var count int64
	cond, vals, errs := WhereBuild(where)
	if errs != nil {
		return 0, errs
	}
	if err := db.Model(&Tag{}).Where(cond, vals...).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}

func CleanTag(where map[string]interface{}) error {
	cond, vals, errs := WhereBuild(where)
	if errs != nil {
		return errs
	}
	if err := db.Unscoped().Where(cond, vals...).Delete(&Tag{}).Error; err != nil {
		return err
	}

	return nil
}
